package com.fenghuaxz.rpcframework.model;

import io.netty.channel.Channel;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class SyncCallback implements MsgCallback {

    public static long SYNC_RPCREQUEST_TIMEOUT_MILLIS = 5*1000;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition signal = lock.newCondition();
    private MsgResponse response = null;

    @Override
    public Object await() throws Exception {
        lock.lock();
        try {
            signal.await(SYNC_RPCREQUEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
            if (response != null){
                String exp = response.getException();
                if (exp != null) throw new Exception(exp);
                return response.getResult();
            }
            throw new Exception("错误:请求超时。");
        }finally {
            lock.unlock();
        }
    }

    @Override
    public void handler(MsgResponse response, Channel channel) throws Exception {
        lock.lock();
        try {
            this.response=response;
            signal.signal();
        }finally {
            lock.unlock();
        }
    }
}
